package com.hduong.springcloud.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Created by dudu on 2020/3/18.
 */
@Service
public class PaymentService {

    public String paymentInfo_Ok(Integer id) {
        return "线程池" + Thread.currentThread().getName() + " paymentOk！";
    }

    //当调用方法 的时间 ： 超过了已经设置的峰值 3 秒的时候 ，就会调用失败的方法 ： fallbackMethod
    //在 消费者 和 服务提供者都可以使用
    @HystrixCommand(fallbackMethod = "payinfo_timeoutHandler", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
    })
    public String timeout(Integer timenumber) {
//        Thread.sleep(3000);
        int timenumber2 = 5;
//        int a = 10 / 0;
//        try {
//            TimeUnit.SECONDS.sleep(timenumber2);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        return "线程池" + Thread.currentThread().getName() + " paymentOk！耗时" + timenumber2 + "秒钟";
    }

    //int 和 Integer 可能导致 出错 ： 因为参数不一样
    public String payinfo_timeoutHandler(Integer timenumber) {
        return "系统服务繁忙! "+"线程池" + Thread.currentThread().getName() + " payinfo_timeoutHandler. ";
    }

    @HystrixCommand(fallbackMethod = "paymentCircuitBreak_fallback", commandProperties = {
            //是否开启断路器
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),
            //请求次数
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
            //时间窗口期
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),
            //失败率达到多少后跳闸
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60")
    })
    public String paymentCircuitBreak(Integer id) {
        if (id < 0) {
            throw new RuntimeException("id 不能为负数;");
        }
        String num = UUID.randomUUID().toString();
        return "线程池" + Thread.currentThread().getName() + "调用成功，流水号" + num;
    }
    public String paymentCircuitBreak_fallback(Integer id) {
        return "id不能为负数，请稍后再试id=" + id;
    }

}
